<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { useCaseStore } from '@/store/kg/case';
import { formRules, getCaseDifficulty, getCaseStatus } from '@/views/kg/case/utils/columns';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { useRenderIcon } from '@/components/CommonIcon/src/hooks';
import Delete from '@iconify-icons/ep/delete';
import EditPen from '@iconify-icons/ep/edit-pen';
import Refresh from '@iconify-icons/ep/refresh';
import Check from '@iconify-icons/ep/check';
import Close from '@iconify-icons/ep/close';
import AddFill from '@iconify-icons/ri/add-circle-fill';
import { Plus, Picture as ElPicture } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import UploadDialogImage from '@/components/Upload/UploadDialogImage.vue';
import { useUserStore } from '@/store/system/user';
import { hasPerms } from '@/utils/auth';

const formRef = ref<FormInstance>();
const tableRef = ref();
const selectIds = ref<number[]>([]);
const caseStore = useCaseStore();
const router = useRouter();
const userStore = useUserStore();

// 案例难度选项
const difficultyOptions = ref([
	{ label: '简单', value: 1 },
	{ label: '中等', value: 2 },
	{ label: '困难', value: 3 },
]);

// 审核对话框
const auditDialogVisible = ref(false);
const auditForm = ref({
	id: null,
	status: 2, // 默认通过
	auditMessage: '',
});

// 分页变化
const handlePageChange = (page: number) => {
	caseStore.currentPage = page;
	caseStore.fetchCaseList();
};

// 每页条数变化
const handleSizeChange = (size: number) => {
	caseStore.pageSize = size;
	caseStore.fetchCaseList();
};

// 重置查询表单
const resetSearchForm = () => {
	caseStore.queryParams = {
		page: 1,
		size: 12,
	};
	caseStore.fetchCaseList();
};

// 删除案例
const handleDelete = (row: any) => {
	ElMessageBox.confirm(`确认删除案例"${row.name || row.description}"吗？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			caseStore.removeCase(row.nodeId);
		})
		.catch(() => {});
};

// 打开审核对话框
const openAuditDialog = (row: any, status: number) => {
	auditForm.value = {
		id: row.nodeId as string,
		status,
		auditMessage: '',
	};
	auditDialogVisible.value = true;
};

// 提交审核
const submitAudit = () => {
	if (auditForm.value.status === 3 && !auditForm.value.auditMessage) {
		ElMessage.warning('拒绝审核时，请填写审核意见');
		return;
	}

	caseStore.performAudit(auditForm.value.id as string, auditForm.value.status, auditForm.value.auditMessage).then(() => {
		auditDialogVisible.value = false;
	});
};

// 提交表单
const submitForm = async () => {
	if (!formRef.value) return;

	await formRef.value.validate(valid => {
		if (valid) {
			caseStore.saveCase().then(() => {
				// 确保提交后重置表单
				caseStore.resetForm();
			});
		}
	});
};

// 上传成功回调
const handleUploadCallback = (result: any) => {
	if (result && result.data && result.data.url) {
		caseStore.formData.cover = result.data.url;
	}
};

// 查看案例详情
const viewCaseDetail = (id: string) => {
	// 在应用内标签页打开详情页，而不是浏览器新标签
	router.push(`/kg/case/detail-view/${id}`);
};

// 判断案例是否可以编辑
const canEditCase = (item: any): boolean => {
	// 检查是否有全局案例编辑权限或全局管理权限
	if (hasPerms('case::all')) {
		return true;
	}

	// 获取当前用户名
	const currentUsername = userStore.username;

	// 检查是否是自己创建的案例
	const isCreatedByCurrentUser = item.createdByUsername === currentUsername;

	// 检查状态是否为草稿(0)或审核未通过(3)
	const isEditableStatus = item.status === 0 || item.status === 3;

	return isCreatedByCurrentUser && isEditableStatus;
};

onMounted(() => {
	caseStore.fetchCaseList();
	caseStore.fetchCaseTypes();
});
</script>

<template>
	<div class="main">
		<!-- 搜索表单 -->
		<el-form :inline="true" :model="caseStore.queryParams" class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto">
			<el-form-item label="案例名称" prop="name">
				<el-input v-model="caseStore.queryParams.name" placeholder="请输入案例名称" class="!w-[180px]" clearable />
			</el-form-item>
			<el-form-item label="案例类型" prop="type">
				<el-select v-model="caseStore.queryParams.type" placeholder="请选择案例类型" class="!w-[180px]" clearable>
					<el-option v-for="type in caseStore.caseTypes" :key="type" :label="type" :value="type" />
				</el-select>
			</el-form-item>
			<el-form-item label="案例难度" prop="difficulty">
				<el-select v-model="caseStore.queryParams.difficulty" placeholder="请选择案例难度" class="!w-[180px]" clearable>
					<el-option v-for="item in difficultyOptions" :key="item.value" :label="item.label" :value="item.value">
						<template #default>
							<el-tag :type="getCaseDifficulty(item.value)" size="small" class="mr-2">{{ item.label }}</el-tag>
							{{ item.label }}
						</template>
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="案例状态" prop="status">
				<el-select v-model="caseStore.queryParams.status" placeholder="请选择案例状态" class="!w-[180px]" clearable>
					<el-option label="草稿" :value="0" />
					<el-option label="审核中" :value="1" />
					<el-option label="已发布" :value="2" />
					<el-option label="审核未通过" :value="3" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button :icon="useRenderIcon('ri:search-line')" :loading="caseStore.loading" type="primary" @click="caseStore.fetchCaseList">搜索 </el-button>
				<el-button :icon="useRenderIcon(Refresh)" @click="resetSearchForm">重置</el-button>
			</el-form-item>
		</el-form>

		<!-- 卡片列表区域 -->
		<div class="card-container p-4">
			<div class="flex justify-between mb-4">
				<h2 class="text-lg font-bold">案例管理</h2>
				<div>
					<el-button :icon="useRenderIcon(AddFill)" type="primary" @click="caseStore.openAddForm">新增案例</el-button>
					<el-button :icon="useRenderIcon(Refresh)" @click="caseStore.fetchCaseList">刷新</el-button>
				</div>
			</div>

			<!-- 卡片列表 -->
			<el-row :gutter="12">
				<el-col v-if="caseStore.caseList.length === 0" :span="24" class="py-8">
					<el-empty description="暂无案例数据" />
				</el-col>
				<el-col v-for="item in caseStore.caseList" :key="item.nodeId" :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb-3">
					<el-card class="card-item h-full cursor-pointer hover:shadow-lg transition-shadow rounded-xl overflow-hidden" :body-style="{ padding: '0px' }" @click="viewCaseDetail(item.nodeId)">
						<div class="card-cover">
							<div v-if="!item.cover" class="empty-cover flex items-center justify-center">
								<el-icon class="text-4xl text-gray-400"><el-picture /></el-icon>
								<div class="mt-2 text-gray-500">暂无封面</div>
							</div>
							<img
								v-else
								:src="item.cover"
								class="w-full h-40 object-cover"
								@error="(e: Event) => {
									if (e.target instanceof HTMLImageElement) {
										e.target.src = 'https://via.placeholder.com/300x200?text=图片加载失败';
									}
								}"
							/>
							<div class="status-tag">
								<el-tag :type="getCaseStatus(item.status || 0)" size="small" class="rounded-lg">
									{{ ['草稿', '审核中', '已发布', '审核未通过', '已下架'][item.status || 0] }}
								</el-tag>
							</div>
						</div>
						<div class="card-content p-3">
							<div class="flex justify-between items-center mb-1">
								<el-tag :type="getCaseDifficulty(item.difficulty || 0)" size="small" class="rounded-lg">
									{{ ['未知', '简单', '中等', '困难'][item.difficulty || 0] }}
								</el-tag>
								<span class="text-xs text-gray-500">{{ typeof item.type === 'string' ? item.type : item.type ? String(item.type) : '未分类' }}</span>
							</div>
							<h3 class="text-sm font-semibold mb-2 line-clamp-2 mt-1">{{ item.name || '未命名案例' }}</h3>
							<div class="flex justify-between mt-2">
								<div class="text-xs text-gray-500">
									{{ item.createTime ? (typeof item.createTime === 'string' && item.createTime.includes('T') ? new Date(item.createTime).toLocaleDateString() : item.createTime) : '' }}
								</div>
								<div class="flex gap-1">
									<el-button v-if="canEditCase(item)" :icon="useRenderIcon(EditPen)" link type="primary" size="small" @click.stop="caseStore.openEditForm(item)" />
									<el-button :icon="useRenderIcon(Delete)" link type="danger" size="small" @click.stop="handleDelete(item)" />
									<el-button v-if="item.status === 0" :icon="useRenderIcon('ri:send-plane-fill')" link type="warning" size="small" @click.stop="caseStore.submitCaseForReview(item.nodeId)" />
									<el-button v-if="item.status === 1" :icon="useRenderIcon(Check)" link type="success" size="small" @click.stop="openAuditDialog(item, 2)" />
									<el-button v-if="item.status === 1" :icon="useRenderIcon(Close)" link type="danger" size="small" @click.stop="openAuditDialog(item, 3)" />
								</div>
							</div>
						</div>
					</el-card>
				</el-col>
			</el-row>

			<!-- 分页 -->
			<div class="flex justify-center mt-6 mb-2">
				<el-pagination
					v-model:currentPage="caseStore.currentPage"
					v-model:page-size="caseStore.pageSize"
					:page-sizes="[12, 24, 36, 48]"
					:total="caseStore.total"
					background
					layout="total, sizes, prev, pager, next, jumper"
					@size-change="handleSizeChange"
					@current-change="handlePageChange"
				/>
			</div>
		</div>

		<!-- 表单弹窗 -->
		<el-dialog :title="caseStore.formType === 'add' ? '新增案例' : '编辑案例'" v-model="caseStore.formVisible" width="600px" :close-on-click-modal="false" :destroy-on-close="true" @closed="caseStore.resetForm()">
			<el-form ref="formRef" :model="caseStore.formData" :rules="formRules" label-width="80px">
				<el-form-item label="封面" prop="cover">
					<UploadDialogImage :image-url="caseStore.formData.cover" type="user" @upload-callback="handleUploadCallback" />
				</el-form-item>
				<el-form-item label="名称" prop="name">
					<el-input v-model="caseStore.formData.name" type="text" placeholder="请输入案例名称" />
				</el-form-item>
				<el-form-item label="描述" prop="description">
					<el-input v-model="caseStore.formData.description" type="textarea" :rows="3" placeholder="请输入案例描述" />
				</el-form-item>
				<el-form-item label="类型" prop="type">
					<el-select v-model="caseStore.formData.type" placeholder="请选择案例类型" class="w-full">
						<el-option v-for="type in caseStore.caseTypes" :key="type" :label="type" :value="type" />
					</el-select>
				</el-form-item>
				<el-form-item label="难度" prop="difficulty">
					<el-select v-model="caseStore.formData.difficulty" placeholder="请选择案例难度" class="w-full">
						<el-option v-for="item in difficultyOptions" :key="item.value" :label="item.label" :value="item.value">
							<template #default>
								<el-tag :type="getCaseDifficulty(item.value)" size="small" class="mr-2">{{ item.label }}</el-tag>
								{{ item.label }}
							</template>
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="caseStore.formVisible = false">取消</el-button>
				<el-button type="primary" :loading="caseStore.loading" @click="submitForm">保存</el-button>
			</template>
		</el-dialog>

		<!-- 审核对话框 -->
		<el-dialog title="案例审核" v-model="auditDialogVisible" width="500px" :close-on-click-modal="false">
			<el-form :model="auditForm" label-width="80px">
				<el-form-item label="审核状态">
					<el-radio-group v-model="auditForm.status">
						<el-radio :value="2" label="通过审核">
							<el-tag type="success" size="small" class="mr-2">通过</el-tag>
							通过审核
						</el-radio>
						<el-radio :value="3" label="拒绝审核">
							<el-tag type="danger" size="small" class="mr-2">拒绝</el-tag>
							拒绝审核
						</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="审核意见" v-if="auditForm.status === 3">
					<el-input v-model="auditForm.auditMessage" type="textarea" :rows="3" placeholder="请输入拒绝审核的原因" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="auditDialogVisible = false">取消</el-button>
				<el-button type="primary" :loading="caseStore.loading" @click="submitAudit">确认</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<style lang="scss" scoped>
:deep(.el-table__inner-wrapper::before) {
	height: 0;
}

.search-form {
	:deep(.el-form-item) {
		margin-bottom: 12px;
	}
}

.card-container {
	background-color: var(--el-bg-color);
	border-radius: 8px;
	padding: 16px;
}

.card-item {
	position: relative;
	transition: all 0.3s;
	border-radius: 12px;
	overflow: hidden;

	.card-cover {
		position: relative;
	}

	.empty-cover {
		height: 160px;
		background-color: #f5f7fa;
		flex-direction: column;
	}

	.status-tag {
		position: absolute;
		top: 8px;
		right: 8px;
		z-index: 1;
	}

	.line-clamp-2 {
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
		height: 2.5rem;
	}
}

.avatar-uploader {
	:deep(.el-upload) {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);

		&:hover {
			border-color: var(--el-color-primary);
		}
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 120px;
		height: 120px;
		text-align: center;
		line-height: 120px;
	}

	.avatar {
		width: 120px;
		height: 120px;
		display: block;
		object-fit: cover;
	}
}
</style>
